function myRecords() {
    var records = "<br><br><br><ul class=\"layui-timeline\">"
    var data = {
        uid: getQueryString("uid")
    }
    $.ajax({
        async:false,
        url:"/allTransactions",
        data:JSON.stringify(data),
        contentType: "application/json;charset=utf-8",
        dataType:"json",
        type:"post",
        success:function(response) {
            if (response['code'] === "200") {
                var allData = response["data"]
                for (let i = 0; i < allData.length; i++) {
                    var tid = allData[i]["tid"]
                    var amount = allData[i]["amount"]
                    var time = allData[i]["time"]
                    var cardId = allData[i]["cardId"]
                    records += "<li class=\"layui-timeline-item\">\n" +
                        "    <i class=\"layui-icon layui-timeline-axis\">&#xe63f;</i>\n" +
                        "    <div class=\"layui-timeline-content layui-text\">\n" +
                        "      <h3 class=\"layui-timeline-title\">"+time+"</h3>\n" +
                        "      <p>\n" +
                        "        订单编号: "+tid+"<br>\n" +
                        "使用卡号: "+cardId+ "<br>"+ "交易金额: "+amount + "&nbsp;&nbsp;" +
                        "<i class=\"layui-icon\"></i>\n" +
                        "      </p>\n" +
                        "    </div>\n" +
                        "  </li><br>"
                }
                records += "</ul>"
                $("#delete").html(records)
            }else {
                layer.msg(response['msg'])
            }
        },
        error:function(){
            alert("服务器请求出现错误")
        }
    })

}

function showFund() {
    $("#delete").html("<table id=\"demo\" lay-filter=\"demo\" ></table>")
    var cards = showCards(5)
    var url = '/allFunds'
    var cols = [
        [
            {field: 'fid', title: '基金ID', width:200, sort: true, fixed: 'left'},
            {field: 'name', title: '基金名称', width:250},
            {field: 'price', title: '基金价格', width:150, sort: true},
            {field: 'manager', title: '基金管理者', width:150, sort: true},
            {field: 'type', title: '基金类型', width: 100},
            {field: 'risk', title: '基金风险等级', width: 100},
            {fixed: 'right', width:200, align:'center', toolbar: '#barDemo'}
        ]
    ]
    var table = showTable(url,cols,1150)
    table.on('tool(demo)', function(obj){
        var data = obj.data;
        var id = data.fid
        var price = data.price
        if(obj.event === 'detail'){
            layerOut('<div style="padding: 20px 100px;">'+ data.description +'</div>','关闭',1,id)
        } else if(obj.event === 'buy') {
            var cardHtml = "<option value=>银行卡</option>"
            for (let i = 0; i < cards.length; i++) {
                var cid = cards[i]["cid"]
                cardHtml += "<option value="+cid+">"+cid+"</option>"
            }
            cardHtml += "<input type=\"number\" id=stockNum required  lay-verify=\"required\" placeholder=\"请输入购买数量\" autocomplete=\"off\" class=\"layui-input\">"

            layerOut("<div class=\"layui-form-item\"><div class=\"layui-input-inline\">\n" +
                "        <select id=quiz1>\n" + cardHtml +
                "        </select>\n" +
                "    </div></div>","购买",2,{id:id,price:price})
        }
    });

}

function showInsure() {
    $("#delete").html("<table id=\"demo\" lay-filter=\"demo\" ></table>")
    var cards = showCards(5)
    var url = '/allInsurances'
    var cols = [
        [
            {field: 'iid', title: '保险ID', width:250, sort: true, fixed: 'left'},
            {field: 'name', title: '保险名称', width:250},
            {field: 'price', title: '保险价格', width:150, sort: true},
            {field: 'type', title: '保险类型', width: 150},
            {fixed: 'right', width:200, align:'center', toolbar: '#barDemo'}
        ]
    ]
    var table = showTable(url,cols,1000)
    table.on('tool(demo)', function(obj){
        var data = obj.data;
        var id = data.iid
        var price = data.price
        if(obj.event === 'detail'){
            layerOut('<div style="padding: 20px 100px;">'+ data.description +'</div>','关闭',1,id)
        } else if(obj.event === 'buy') {
            var cardHtml = "<option value=>银行卡</option>"
            for (let i = 0; i < cards.length; i++) {
                var cid = cards[i]["cid"]
                cardHtml += "<option value="+cid+">"+cid+"</option>"
            }
            cardHtml += "<input type=\"number\" id=stockNum required  lay-verify=\"required\" placeholder=\"请输入购买数量\" autocomplete=\"off\" class=\"layui-input\">"

            layerOut("<div class=\"layui-form-item\"><div class=\"layui-input-inline\">\n" +
                "        <select id=quiz1>\n" + cardHtml +
                "        </select>\n" +
                "    </div></div>","购买",2,{id:id,price:price})
        }
    });

}

function showStock() {
    $("#delete").html("<table id=\"demo\" lay-filter=\"demo\" ></table>")
    var cards = showCards(5)
    var url = '/allStocks'
    var cols = [
        [
            {field: 'sid', title: '股票ID', width:200, sort: true, fixed: 'left'},
            {field: 'name', title: '股票名称', width:250},
            {field: 'price', title: '股票价格', width:150, sort: true},
            {field: 'type', title: '股票类型', width: 100},
            {field: 'risk', title: '股票风险等级', width: 100},
            {fixed: 'right', width:200, align:'center', toolbar: '#barDemo'}
        ]
    ]
    var table = showTable(url,cols,1000)

    table.on('tool(demo)', function(obj){
        var data = obj.data;
        var id = data.sid
        var price = data.price
        if(obj.event === 'detail'){
            layerOut('<div style="padding: 20px 100px;">'+ data.description +'</div>','关闭',1,id)
        } else if(obj.event === 'buy') {
            var cardHtml = "<option value=>银行卡</option>"
            for (let i = 0; i < cards.length; i++) {
                var cid = cards[i]["cid"]
                cardHtml += "<option value="+cid+">"+cid+"</option>"
            }
            cardHtml += "<input type=\"number\" id=stockNum required  lay-verify=\"required\" placeholder=\"请输入购买数量\" autocomplete=\"off\" class=\"layui-input\">"

            layerOut("<div class=\"layui-form-item\"><div class=\"layui-input-inline\">\n" +
                "        <select id=quiz1>\n" + cardHtml +
                "        </select>\n" +
                "    </div></div>","购买",2,{id:id,price:price})
        }
    });

}

function initUser() {
    $("#delete").html("<table id=\"demo\" lay-filter=\"demo\" ></table>")
    var url = '/allAssets?uid='+getQueryString("uId")
    var cols = [
        [
            {field: 'aid', title: '资产ID', width:200, sort: true, fixed: 'left'}
            ,{field: 'product', title: '资产名称', width:250}
            ,{field: 'price', title: '购买价格', width:120, sort: true}
            ,{field: 'num', title: '购买数量', width:120}
            ,{field: 'type', title: '资产类型', width: 140, sort: true}
            ,{field: 'income', title: '收益', width: 120, sort: true}
            ,{field: 'date', title: '购买日期', width: 200, sort: true}
        ]
    ]
    var data = []

    showTable(url,cols,1050)


}

function showTable(urls,cols,width) {
    var table;
    layui.use('table', function(){
        table = layui.table;
        //第一个实例
        table.render({
            elem: '#demo'
            ,height: 'full-50'
            ,width: width
            ,url: urls
            ,page: true //开启分页
            ,cols: cols
            ,limit:10
        });
    });
    return table
}

function showCard() {
    $("#delete").html("")

    $.ajax({
        async:false,
        url:"/myCards?uid="+getQueryString("uId"),
        contentType: "application/json;charset=utf-8",
        dataType:"json",
        type:"get",
        success:function(response) {
            var list = response["data"]
            console.log(list)
            var allHtml = "";
            for (let i = 0; i < list.length; i++) {
                var cid = list[i]["cid"]
                var type = list[i]["type"]
                var balance = list[i]["balance"]
                var issueDate = list[i]["issueDate"]
                var limit = list[i]["limit"]
                var bgcolor = "#fdfdfd"
                if (type === "储蓄卡") {
                }else {
                    bgcolor = "rgba(236,236,236,0.88)"
                }
                allHtml += "<div class=\"layui-card\" style=\"background-color: "+bgcolor+"\">\n" +
                    "            <div class=\"layui-card-header\">"+"卡号: "+cid+"</div>\n" +
                    "            <div class=\"layui-card-body\">\n" +
                    "                银行卡类型:"+type+"<br>\n" +
                    "                银行卡余额:"+balance+"元<br>\n" +
                    "                银行卡创建日期:" + issueDate +"<br>\n"+
                    "                银行卡可透支额度:" +limit+ "元" +
                    "            </div>\n" +
                    "        </div><br><hr><br>"

            }
            $("#delete").html("<br><br>"+allHtml)
        },
        error:function(){
            alert("服务器请求出现错误")
        }
    })
}

function showCards(nums) {
    var ret;
    $.ajax({
        async:false,
        url:"/myCards?uid="+getQueryString("uId"),
        dataType:"json",
        type:"get",
        success:function(response) {
            ret = response['data']
        },
        error:function(){
            alert("服务器请求出现错误")
        }
    })
    return ret
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

function getNewCard() {
    var html = ""

    html += " <br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<select id=switch >\n" +
        "        <option value=请选择></option>\n" +
        "        <option value=\"0\">信用卡</option>\n" +
        "        <option value=\"1\">储蓄卡</option>\n" +
        "      </select>"

    html += "<br><br><br><form class=\"layui-form\" action=\"\"><div class=\"layui-form-item\">\n" +
        "    <label class=\"layui-form-label\">支付密码</label>\n" +
        "    <div class=\"layui-input-inline\">\n" +
        "      <input type=\"password\" name=\"password\" id='password' required lay-verify=\"required\" placeholder=\"请输入密码\" autocomplete=\"off\" class=\"layui-input\">\n" +
        "    </div>\n" +
        "  </div>"

    html += "<button type=\"button\"  onclick='createNewCard()' class=\"layui-btn layui-btn-radius layui-btn-normal\">创建</button>"

    $("#delete").html(html)
}

function createNewCard() {
    var type = $("#switch").val()
    var password = $("#password").val()
    if (type === "请选择") {
        alert("请选择银行卡类型")
    }else if (password === "") {
        alert("请输入密码")
    }else{
        var data = {
            uid: getQueryString("uid"),
            type: type,
            password: md5(password)
        }
        $.ajax({
            async:true,
            url:"/applyNewCard",
            data:JSON.stringify(data),
            contentType: "application/json;charset=utf-8",
            dataType:"json",
            type:"post",
            success:function(response) {
                if (response['code'] === "200") {
                    alert("你创建的卡号为:"+response['msg'])
                    showCards()
                }else {
                    alert(response['msg'])
                }
            },
            error:function(){
                alert("服务器请求出现错误")
            }
        })
    }
}

function layerOut(html,close,num,idAndPrice) {
    var stockID = idAndPrice["id"]
    var price = idAndPrice["price"]

    layui.use('layer', function(){ //独立版的layer无需执行这一句
        var $ = layui.jquery, layer = layui.layer; //独立版的layer无需执行这一句
        layer.open({
            type: 1
            ,offset: 'auto' //具体配置参考：https://www.layuiweb.com/doc/modules/layer.html#offset
            ,id: 'layerDemo'+'auto' //防止重复弹出
            ,content: html
            ,btn: close
            ,btnAlign: 'c' //按钮居中
            ,shade: 0 //不显示遮罩
            ,yes: function(){
                if (num === 1) {
                    layer.closeAll();
                }else if(num === 2) {
                    // 购买股票
                    var idCard = $("#quiz1").val().trim()
                    var stockNum = $("#stockNum").val().trim()
                    if (stockNum === "") {
                        alert("购买数量不能为空")
                    }else if(idCard === "") {
                        alert("未选择银行卡")
                    }else {
                        var data = {
                            uid: getQueryString("uid"),
                            pid: stockID,
                            num: stockNum,
                            price: price,
                            cid: idCard
                        }
                        $.ajax({
                            async:true,
                            url:"/buy",
                            data:JSON.stringify(data),
                            contentType: "application/json;charset=utf-8",
                            dataType:"json",
                            type:"post",
                            success:function(response) {
                                if (response['code'] === "200") {

                                    layer.closeAll();
                                    layer.msg("购买成功")
                                    initUser();
                                }else {
                                    layer.closeAll();
                                    alert(response['msg'])
                                }
                            },
                            error:function(){
                                alert("服务器请求出现错误")
                            }
                        })
                    }
                }
            }
        });
        $('#layerDemo .layui-btn').on('click', function(){
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
    });
}
